<?php

class Install_Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{

	protected function _initAutoloader()
	{
		$autoloader = new Zend_Application_Module_Autoloader( array(
				'namespace' => 'Install',
				'basePath' => INSTALL_PATH,
		));

		Zend_Registry::set('Autoloader', $autoloader);

		return $autoloader;
	}
    

	protected function _initLog()
	{
		$log = new Zend_Log();
		
		$filename = LOG_PATH. '/install.log'; 
		

		// Non-production
		if (APPLICATION_ENV !== 'production')
		{
			$log -> addWriter(new Zend_Log_Writer_Firebug());
		}

		// Production
		try
		{
			$log -> addWriter(new Zend_Log_Writer_Stream($filename));
		}
		catch( Exception $e )
		{
			// Check directory
			if (!@is_dir(LOG_PATH) && @mkdir(LOG_PATH, 0777, true))
			{
				$log -> addWriter(new Zend_Log_Writer_Stream($filename));
			}
			else
			{
				// Silence ...
				if (APPLICATION_ENV !== 'production')
				{
					$log -> log($e -> __toString(), Zend_Log::CRIT);
				}
				else
				{
					// Make sure logging doesn't cause exceptions
					$log -> addWriter(new Zend_Log_Writer_Null());
				}
			}
		}

		Zend_Registry::set('Zend_Log', $log);
		Nuo::registerErrorHandlers();

		if ('production' != APPLICATION_ENV)
		{
			// Nuo_Exception::setLog($log);
		}

		return $log;
	}

	protected function _initCache()
	{
		if (is_writable(CACHE_PATH) || (!@is_dir(CACHE_PATH) && @mkdir(CACHE_PATH, 0777, true)))
		{

			try
			{

				$cache = Zend_Cache::factory('Core', 'File', array('automatic_serialization' => true, ), array(
						'cache_dir' => CACHE_PATH,
						'file_name_prefix' => 'EngineInstall',
				));

				Zend_Registry::set('Cache', $cache);

				return $cache;

			}
			catch( Exception $e )
			{

			}
		}
	}

	protected function _initRouter()
	{
		$front = Zend_Controller_Front::getInstance();

		$router = $front -> getRouter();
		//$router = new Zend_Controller_Router_Rewrite();
		$router -> addRoute('setup', new Zend_Controller_Router_Route('setup/:action', array(
				'controller' => 'setup',
				'action' => 'license',
		)));
		$router -> addRoute('manage', new Zend_Controller_Router_Route('manage/:action', array(
				'controller' => 'manage',
				'action' => 'index',
		), array('action' => 'index|ftp|upload|browse', )));
		$router -> addRoute('sdk', new Zend_Controller_Router_Route('sdk/:action', array(
				'controller' => 'sdk',
				'action' => 'index',
		), array('action' => 'index|create|build|manage|delete', )));
		$router -> addRoute('login', new Zend_Controller_Router_Route_Static('login', array(
				'controller' => 'auth',
				'action' => 'login',
		)));
		$router -> addRoute('logout', new Zend_Controller_Router_Route_Static('logout', array(
				'controller' => 'auth',
				'action' => 'logout',
		)));
		return $router;
	}
	
  protected function _initSession()
  {
    $name = 'nuoInstall';
		
    Zend_Session::setOptions(array(
      'name' => $name,
      'cookie_path' => substr($_SERVER['SCRIPT_NAME'], 0, strrpos($_SERVER['SCRIPT_NAME'], '/')+1),
      'cookie_lifetime' => 0, //86400,
      'gc_maxlifetime' => 86400,
      'remember_me_seconds' => 86400,
      'cookie_httponly' => false,
    ));
    session_name($name);

    // Check for bad session config
    if( function_exists('ini_get') &&
        in_array(strtolower(ini_get('session.save_handler')), array('user', 'users', 'files')) ) {
  
      $flag = true;
      if ('files'  !== ini_get('session.save_handler') && function_exists('ini_set')) {
         $flag = false !== ini_set('session.save_handler', 'files');
      }
			
			if(!@is_dir(SESSION_PATH) && @mkdir(SESSION_PATH, 0777, true)){
				
			}
      
      if( function_exists('ini_set') && $flag &&
          false !== ini_set('session.save_path', SESSION_PATH) ) {
        if( !is_writable(SESSION_PATH) ) {
          throw new Exception('Please set full permissions on '.SESSION_PATH.' (chmod 0777).');
        }
      } else {
        throw new Exception('Your session configuration is incorrect and ' .
            'could not be automatically corrected. Please set ' .
            'session.save_handler=files and session.save_path=/tmp (or your ' .
            'temporary directory on non-Linux OSes.');
      }
    }
    
    // Session hack for fancy upload
    if( isset($_POST[session_name()]) ) {
      Zend_Session::setId($_POST[session_name()]);
    } else if( isset($_COOKIE[session_name()]) ) {
      Zend_Session::setId($_COOKIE[session_name()]);
    }
    
    // Start
    try {
      Zend_Session::start();
    } catch( Exception $e ) { // This will generally happen when weird data is saved during the install process
      if( Zend_Session::isStarted() ) {
        Zend_Session::destroy();
      }
      throw $e;
    }

    // Session binding
    $fixed = true;
    $namespace = new Zend_Session_Namespace('ZendSession');
    if( empty($namespace->ip) /* || empty($namespace->ua)*/ ) {
      $namespace->ip = $_SERVER['REMOTE_ADDR'];
      $namespace->ua = @$_SERVER['HTTP_USER_AGENT'];
    } else if( $namespace->ip != $_SERVER['REMOTE_ADDR'] /* || $namespace->ua != $_SERVER['HTTP_USER_AGENT']*/ ) {
      $fixed = false;
    }

    if( !$fixed ) {
      Zend_Session::destroy();
      header('Location: ' . $_SERVER['REQUEST_URI']);
      exit();
    }
  }
	protected function _initTranslate()
  {
    // If in development, log untranslated messages
    $params = array(
      'scan' => Zend_Translate_Adapter::LOCALE_FILENAME,
      'logUntranslated' => true
    );

    $log = new Zend_Log();
    if( APPLICATION_ENV == 'development' ) {
      $log = new Zend_Log();
      $log->addWriter(new Zend_Log_Writer_Firebug());
    } else {
      $log->addWriter(new Zend_Log_Writer_Null());
    }
    $params['log'] = $log;

    $translate = new Zend_Translate(
      'Csv',
      INSTALL_PATH.'/languages',
      null,
      $params
    );

    Zend_Registry::set('Zend_Translate', $translate);
    Zend_Validate_Abstract::setDefaultTranslator($translate);

    Zend_Registry::set('Locale', new Zend_Locale());

    return $translate;
  }

	protected function _initView()
  {
    $view = new Zend_View();
    $view->setEncoding('utf-8');

    $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
    $viewRenderer->setView($view);

    $view->addHelperPath(LIBRARY_PATH . '/Nuo/View/Helper', 'Nuo_View_Helper');
    $view->addHelperPath(INSTALL_PATH . '/views/helpers', 'Install_View_Helper');
    
    Zend_Registry::set('Zend_View', $view);
    
    return $view;
  }

	protected function _initLayout()
  {
    // Create layout
    $layout = Zend_Layout::startMvc();

    // Set options
    $layout->setViewBasePath(INSTALL_PATH . "/layouts", 'Install_Layout_View')
      ->setLayout('index');

    return $layout;
  }
	
	protected function _initFrontController()
	{
		$front = Zend_Controller_Front::getInstance();
	    
		$front->addControllerDirectory(INSTALL_PATH . '/controllers');
	// Hack
		if( empty($_SERVER['SCRIPT_FILENAME']) ) {
	  		$_SERVER['SCRIPT_FILENAME'] = dirname(dirname(__FILE__)) . $_SERVER['PHP_SELF'];
	    }
	    return $front;
	}
    
    protected function _initHook(){
        Nuo::setHooks(array(
            'onInstallPageStart'=>array(array('Install_Plugin_Hook','onInstallPageStart'))
        ));
    }

	protected function _initDb()
	{
    if( file_exists(APPLICATION_PATH . '/settings/database.php') ) {
      $config = include APPLICATION_PATH . '/settings/database.php';
      if( !empty($config['adapter']) ) {
        try {
          $db = Zend_Db::factory($config['adapter'], $config['params']);
          $db->getServerVersion(); // Forces the connection open
        } catch( Exception $e ) {
          
          return;
        }
        Zend_Registry::set('Zend_Db', $db);

        // set DB to UTC timezone for this session
        switch ($config['adapter']) {
          case 'mysqli':
          case 'mysql':
          case 'pdo_mysql': {
              $db->query("SET time_zone = '+0:00'");
              break;
          }

          case 'postgresql': {
              $db->query("SET time_zone = '+0:00'");
              break;
          }

          default: {
            // do nothing
          }
        }

        // attempt to disable strict mode
        try {
          $db->query("SET SQL_MODE = ''");
        } catch (Exception $e) {}

        Zend_Db_Table_Abstract::setDefaultAdapter($db);

        return $db;
      }
    }
  }
}
